var swayAudio = document.getElementById("audio");
var musicIcon = document.getElementById("musicIcon");
var sway = document.getElementById("sway");
var swayCanvas = document.getElementById("swayCanvas");
// var loopSpan = document.getElementById("loop");
var downloadDiv = document.getElementById("download");
var sliderHorizontal = document.getElementById("sliderHorizontal");
var sliderVertical = document.getElementById("sliderVertical");
// var topicDiv = document.getElementById("topic");
// var loadingFrame = document.getElementById("loadingFrame");
// var loadingDiv = document.getElementById("loadingDiv");
var loadingPhone = document.getElementById("loadingPhone");
var loadingTip = document.getElementById("loadingTip");
var loadingContainer = document.getElementById("loadingContainer");
var guideContainer = document.getElementById("guideContainer");
var downloadProcessHorizontal = document.getElementById("downloadProcessHorizontal");
var downloadProcessVertical = document.getElementById("downloadProcessVertical");
var screenWidth = document.documentElement.clientWidth;
var screenHeight = document.documentElement.clientHeight;
var swayCanvasContext = swayCanvas.getContext("2d");
sway.style.width = screenWidth + "px";
sway.style.height = screenHeight + "px";
downloadDiv.style.width = screenWidth + "px";
downloadDiv.style.height = screenHeight + "px";
swayCanvas.width = screenWidth * 2;
swayCanvas.height = screenHeight * 2;
swayCanvas.style.width = screenWidth + "px";
swayCanvas.style.height = screenHeight + "px";
var sliderController = {
	maxRight: screenWidth - 100,
	maxBottom: screenHeight - 100
};
var imgs = {};
var count = 0;
var guideShow = true;
var angle = 0;
var index = Math.round(imageNum / 2);
var touching = 0;
var mouseEnter = 0;
var lastTime = 0;
var maxAngle = imageNum / 6;
var lastX = 0;
var direction = "horizontal";
var positive = true;
if (directionX === 0) {
	direction = "vertical";
	if (directionY === -1) {
		positive = false
	}
} else {
	if (directionX === -1) {
		positive = false
	}
}
var loopController = {
	last_i: 0,
	direction: "",
	last_direction: "",
	loop: initLoop
};
var downloadController = {
	// begin_index: positive ? imageNum - 20 : 20,
	// end_index: positive ? imageNum - 10 : 10,
    begin_index: positive ? parseInt(imageNum*0.85) : 20,
    end_index: positive ? parseInt(imageNum*0.92) : 10,
	available: false
};
var musicHandler = function() {
	if (swayAudio.paused) {
		swayAudio.play()
	} else {
		swayAudio.pause()
	}
};

//判断是否安装app，没有这跳转到下载
for(var i = 0; i < getElementsByClass('download').length; i++) {
    getElementsByClass('download')[i].onclick = function () {
// document.getElementById('downloadButton').onclick = function () {
        console.log('getApp');
        var ua = navigator.userAgent.toLowerCase();
        var config = {
			/*scheme:必须*/
            scheme_IOS: 'Coolface://',
            scheme_Adr: 'app://com.yxkj.youdoneed',
            // download_IOS: 'https://www.pgyer.com/IuLm',
            // download_Adr: 'https://www.pgyer.com/E8SB',
            download_IOS: 'itms-apps://itunes.apple.com/us/app/coolface/id1246578323?l=zh&ls=1&mt=8',
            download_Adr: 'http://a.app.qq.com/o/simple.jsp?pkgname=com.yxkj.youdoneed',
            timeout: 600
        };
        openclient();
        function openclient() {
            var startTime = Date.now();
            var ifr = document.createElement('iframe');
            ifr.src = ua.indexOf('os') > 0 ? config.scheme_IOS : config.scheme_Adr;
            ifr.style.display = 'none';
            document.body.appendChild(ifr);
            var t = setTimeout(function() {
                var endTime = Date.now();
                if (!startTime || endTime - startTime < config.timeout + 200) { //如果装了app并跳到客户端后，endTime - startTime 一定> timeout + 200
                    window.location = ua.indexOf('os') > 0 ? config.download_IOS : config.download_Adr;
                }
            }, config.timeout);
            window.onblur = function() {
                clearTimeout(t);
            }
        }
    };
}

function getElementsByClass(classnames){
    var classobj = new Array();
    var classint = 0;
    var tags =document.getElementsByTagName("*");
    for(var i in tags){
        if(tags[i].nodeType == 1){
            if(tags[i].getAttribute("class") && tags[i].getAttribute("class").indexOf(classnames) > -1){
                classobj[classint] = tags[i];
                classint++;
            }
        }
    }
    return classobj;
}

(function() {
	loadingContainer.style.height = screenHeight;
	if (musicIcon && swayAudio) {
		musicIcon.addEventListener("click", musicHandler, false);
		swayAudio.addEventListener("play",
		function() {
			musicIcon.src = "/lib/images/landing_v2/music_on.png"
		});
		swayAudio.addEventListener("pause",
		function() {
			musicIcon.src = "/lib/images/landing_v2/music_off.png"
		})
	}
	document.getElementById("downloadButton").addEventListener("click", download, false);
	if (direction === "vertical") {
		document.getElementById("sliderHorizontalContainer").style.display = "none";
		loadingPhone.src = "./image/guide_direction_left.png";
		loadingPhone.setAttribute("class", "square-spin-y");
		// document.getElementById("loopImg").src = "./image/home_video_direction_left.png";
		if (positive) {
			loadingTip.innerHTML = "请向前倾斜手机";
			downloadProcessVertical.style.top = 0
		} else {
			loadingTip.innerHTML = "向后倾斜手机";
			downloadProcessVertical.style.bottom = 0
		}
	}
	if (direction === "horizontal") {
		document.getElementById("sliderVerticalContainer").style.display = "none";
		loadingPhone.src = "./image/guide_direction_left.png";
		loadingPhone.setAttribute("class", "square-spin-x");
		// document.getElementById("loopImg").src = "./image/home_video_direction_left.png";
		if (positive) {
			loadingTip.innerHTML = "请向右倾斜手机";
			downloadProcessHorizontal.style.left = 0
		} else {
			loadingTip.innerHTML = "请向左倾斜手机";
			downloadProcessHorizontal.style.right = 0
		}
	}
	function e(n) {
		var o = new XMLHttpRequest;
		o.open("get", cdnDomain + imagePrefix + "-" + n + ".jpg", true);
		o.responseType = "blob";
		o.onload = function() {
			if (this.readyState === 4 && (this.status === 200 || this.status === 304)) {
				var o = document.createElement("img");
				o.onload = function() {
					window.URL.revokeObjectURL(o.src)
				};
				o.onerror = function() {
					e(n)
				};
				o.src = window.URL.createObjectURL(this.response);
				imgs[n] = {
					times: imgs[n].times + 1,
					success: true,
					src: o
				};
				count++;
				var t = count >= 30 ? 0 : 20 - count / 30 * 20;
				var a = count >= 30 ? 0 : 1 - count / 30;
				// loadingFrame.style.WebkitFilter = "blur(" + t + "px)";
				// loadingDiv.style.opacity = a;
				if (direction === "horizontal") {
					downloadProcessHorizontal.style.width = count / imageNum * 100 + "%"
				} else {
					downloadProcessVertical.style.height = count / imageNum * 100 + "%"
				}
				if (count === 30) {
					i();
					sliderHorizontal.style.display = "block";
					sliderVertical.style.display = "block"
				}
			}
		};
		o.onerror = function() {
			if (imgs[n]) {
				if (imgs[n].times <= 4) {
					imgs[n].times = imgs[n].times + 1;
					e(n)
				} else {
					count++;
					var o = count >= 30 ? 0 : 20 - count / 30 * 20;
					var t = count >= 30 ? 0 : 1 - count / 30;
					// loadingFrame.style.WebkitFilter = "blur(" + o + "px)";
					// loadingDiv.style.opacity = t;
					if (direction === "horizontal") {
						downloadProcessHorizontal.style.width = count / imageNum * 100 + "%"
					} else {
						downloadProcessVertical.style.height = count / imageNum * 100 + "%"
					}
					if (count === 30) {
						i();
						sliderHorizontal.style.display = "block";
						sliderVertical.style.display = "block"
					}
				}
			}
		};
		o.send()
	}
	function i() {
		lastTime = new Date;
		loadingContainer.style.opacity = 0;
		loadingContainer.style.display = "none";
		// topicDiv.style.display = "";
		if (window.DeviceMotionEvent) {
			window.addEventListener("devicemotion", d, false)
		} else {
			document.body.innerHTML = "Not supported on your device."
		}
		if (v()) {
			downloadDiv.addEventListener("touchmove", c, false);
			downloadDiv.addEventListener("touchstart", r, false);
			downloadDiv.addEventListener("touchend", s, false)
		} else {
			window.addEventListener("mousemove", u, false);
			downloadDiv.addEventListener("mousedown", m, false);
			window.addEventListener("mouseup", g, false)
		}
	}
	function n() {
		document.getElementById("initCover").style.display = "none";
		for (var i = 1; i <= imageNum; i++) {
			imgs[i] = {
				times: 0,
				success: false,
				src: ""
			};
			e(i)
		}
	}
	function o(e) {
		if (imgs[e] && imgs[e].success && imgs[e].src && imgs[e].times <= 4) {
			var i = imgs[e].src;
			if (i != "") {
				swayCanvasContext.drawImage(i, 0, 0, swayCanvas.width, swayCanvas.width / i.width * i.height)
			}
			var n = e / imageNum;
			sliderHorizontal.style.left = (e === 1 ? 0 : n) * sliderController.maxRight + "px";
			sliderVertical.style.top = (e === 1 ? 0 : n) * sliderController.maxBottom + "px";
			if (e % 10 === 0) {
				t(e)
			}
			a(e);
			l(e)
		}
	}
	function t(e) {
		if (e !== loopController.last_i) {
			if (e >= loopController.last_i) {
				loopController.direction = "front"
			} else {
				loopController.direction = "back"
			}
			// if (loopController.direction !== loopController.last_direction) {
			// 	loopController.loop++;
			// 	loopSpan.innerHTML = loopController.loop
			// }
			loopController.last_i = e;
			loopController.last_direction = loopController.direction
		}
	}
	function a(e) {
		var i;
		var n;
		if (positive) {
			if (e >= downloadController.begin_index && e <= downloadController.end_index) {
				i = (e - downloadController.begin_index) / 10;
				n = e - downloadController.begin_index + "px";
				downloadController.available = true;
				// downloadDiv.style.opacity = i;
				// swayCanvas.style.WebkitFilter = "blur(" + n + ")"
			}
			if (e < downloadController.begin_index) {
				n = "0px";
				i = 0;
				downloadController.available = false;
				// downloadDiv.style.opacity = i;
				// swayCanvas.style.WebkitFilter = "blur(" + n + ")"
			}
		} else {
			if (e >= downloadController.end_index && e <= downloadController.begin_index) {
				i = (downloadController.begin_index - e) / 10;
				n = downloadController.begin_index - e + "px";
				downloadController.available = true;
				// downloadDiv.style.opacity = i;
				// swayCanvas.style.WebkitFilter = "blur(" + n + ")"
			}
			if (e > downloadController.begin_index) {
				n = "0px";
				i = 0;
				downloadController.available = false;
				// downloadDiv.style.opacity = i;
				// swayCanvas.style.WebkitFilter = "blur(" + n + ")"
			}
		}
	}
	function l(e) {
		if (positive) {
			if (e >= 10 && e <= 20) {
				// topicDiv.style.opacity = (20 - e) / 10
			}
			if (e > 20) {
				// topicDiv.style.opacity = 0
			}
			if (guideShow && e > 20) {
				guideContainer.style.display = "none"
			}
		} else {
			if (e >= imageNum - 20 && e <= imageNum - 10) {
				// topicDiv.style.opacity = (e - (imageNum - 20)) / 10
			}
			if (e < imageNum - 20) {
				// topicDiv.style.opacity = 0
			}
			if (guideShow && e < imageNum - 20) {
				guideContainer.style.display = "none"
			}
		}
	}
	function d(e) {
		if (touching === 0) {
			var i = new Date - lastTime;
			var n = 0;
			if (direction === "horizontal") {
				n = e.rotationRate.beta;
				if (!positive) {
					n = -n
				}
				if(isAndroid()){
					n = n / 3.14 * 180;       //角速度 角度
				}
			}
			if (direction === "vertical") {
				n = e.rotationRate.alpha;
				if (!positive) {
					n = -n
				}
				
				if(isAndroid()){
					n = n / 3.14 * 180;       //角速度 角度
				}
			}
			n = n > 60 ? 60 : n;
			n = n < -60 ? -60 : n;
			var t = n * i / 1e3;
			angle = angle + t;
			if (angle < 0) {
				angle = 0
			}
			if (angle > maxAngle) {
				angle = maxAngle
			}
			index = Math.round((angle / maxAngle) * imageNum);
			if (!positive) {
				index = imageNum + 1 - index
			}
			index = index < 1 ? 1 : index;
			index = index > imageNum ? imageNum: index;
			// alert(index)
			o(index);
			lastTime = new Date
		}
	}
	function r(e) {
		if (direction === "horizontal") {
			lastX = Math.round(e.touches[0].clientX)
		}
		if (direction === "vertical") {
			lastX = Math.round(e.touches[0].clientY)
		}
		touching = 1
	}
	function s(e) {
		touching = 0
	}
	function c(e) {
		var i = 0;
		if (direction === "horizontal") {
			i = Math.round(e.touches[0].clientX)
		}
		if (direction === "vertical") {
			i = Math.round(e.touches[0].clientY)
		}
		angle = angle + (i - lastX) / 4;
		angle = angle < 0 ? 0 : angle;
		angle = angle > maxAngle ? maxAngle: angle;
		index = Math.round(angle / maxAngle * imageNum);
		if (!positive) {
			index = imageNum + 1 - index
		}
		index = index < 1 ? 1 : index;
		index = index > imageNum ? imageNum: index;
		o(index);
		lastX = i
	}
	function m(e) {
		mouseEnter = 1
	}
	function g(e) {
		mouseEnter = 0
	}
	function u(e) {
		if (mouseEnter === 1) {
			var i = 0;
			i = e.clientX;
			angle = angle + (i - lastX) / 8;
			angle = angle < 0 ? 0 : angle;
			angle = angle > maxAngle ? maxAngle: angle;
			index = Math.round(angle / maxAngle * imageNum);
			index = index < 1 ? 1 : index;
			index = index > imageNum ? imageNum: index;
			o(index);
			lastX = i
		}
	}
	function v() {
		var e = navigator.userAgent.toLowerCase(),
		i = e.match(/ipad/i) == "ipad",
		n = e.match(/iphone os/i) == "iphone os",
		o = e.match(/midp/i) == "midp",
		t = e.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
		a = e.match(/ucweb/i) == "ucweb",
		l = e.match(/android/i) == "android",
		d = e.match(/windows ce/i) == "windows ce",
		r = e.match(/windows mobile/i) == "windows mobile",
		s = e.match(/webview/i) == "webview";
		return i || n || o || t || a || l || d || r
	}
	function p() {
		var e = navigator.userAgent.toLowerCase();
		if (e.indexOf("fb") == -1) {
			return false
		} else {
			return true
		}
	}
	function isAndroid(){
		var u = navigator.userAgent;
		if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
				return true;
		}
		else{
				return false;
		}
}
	setTimeout(n, 100)
})();